// Java Record示例 (需要Java 16+)

// 1. 基本Record
record Person(String name, int age) {
    // 可以添加自定义方法
    public String greeting() {
        return "Hello, " + name + "!";
    }
}

// 2. 密封接口 + Record模式匹配
sealed interface Shape permits Circle, Rectangle {
    double area();
}

record Circle(double radius) implements Shape {
    @Override
    public double area() {
        return Math.PI * radius * radius;
    }
}

record Rectangle(double width, double height) implements Shape {
    @Override
    public double area() {
        return width * height;
    }
}

// 3. 复杂Record
record Employee(
    String id,
    Person person,
    double salary
) {
    // 紧凑构造器（验证逻辑）
    public Employee {
        if (salary < 0) {
            throw new IllegalArgumentException("Salary cannot be negative");
        }
    }
    
    // 静态工厂方法
    public static Employee create(String id, String name, int age, double salary) {
        return new Employee(id, new Person(name, age), salary);
    }
}

public class JavaRecordExample {
    public static void main(String[] args) {
        System.out.println("=== Java Record示例 ===");
        
        // 基本Record使用
        Person person = new Person("Alice", 30);
        System.out.println("Person: " + person);
        System.out.println("Name: " + person.name());
        System.out.println("Age: " + person.age());
        System.out.println("Greeting: " + person.greeting());
        
        System.out.println("\n=== 模式匹配示例 ===");
        
        // 密封类和模式匹配
        Shape circle = new Circle(5.0);
        Shape rectangle = new Rectangle(4.0, 6.0);
        
        System.out.println("Circle area: " + calculateArea(circle));
        System.out.println("Rectangle area: " + calculateArea(rectangle));
        
        System.out.println("\n=== 复杂Record示例 ===");
        
        // 复杂Record使用
        Employee emp = Employee.create("E001", "Bob", 25, 50000.0);
        System.out.println("Employee: " + emp);
        System.out.println("Employee person: " + emp.person());
    }
    
    // 模式匹配方法 (Java 17+)
    public static double calculateArea(Shape shape) {
        if (shape instanceof Circle c) {
            return c.area();
        } else if (shape instanceof Rectangle r) {
            return r.area();
        }
        return 0;
    }
    
    // 传统的instanceof方式
    public static double calculateAreaTraditional(Shape shape) {
        if (shape instanceof Circle c) {
            return c.area();
        } else if (shape instanceof Rectangle r) {
            return r.area();
        }
        return 0;
    }
}